<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-debt-wrap">
    <explanation :explanation="explanationObj" is-expand class="explanation" style="margin: 0;"/>
    <div class="page-container mobile-small-padding">
      <SectionTitle title="基础信息" style="margin-bottom: 16px;" />
      <el-form
        ref="baseform"
        :rules="rules"
        :model="paramsObj"
        :label-position="formAlign"
        class="lineHeight32"
        label-width="110px">
        <el-row class="response-el-row" type="flex">
          <el-col :span="12">
            <el-form-item label="创建人：" class="grey-label no-required">
              <CheckUserInfo v-if="userInfo.userName" :label="userInfo.userName" :user-id="userInfo.id" />
              <div v-else>--</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="departmentId">
              <el-cascader
                v-model="paramsObj.departmentId"
                :show-all-levels="false"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                filterable
                class="width240"
                placeholder="请选择所属部门"
                size="small">
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <SectionTitle title="转交信息" style="margin-bottom: 16px;" />
        <el-row class="response-el-row" type="flex">
          <el-col :span="12">
            <el-form-item label="转交人" prop="passerId">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="paramsObj.passerObj"
                :hide-select-list="passerHideSelect"
                :multiple="false"
                :value-type="'object'"
                :show-check-user="true"
                :disabled="!hasPasserAuth"
                key-name="id"
                class="width240"
                label-name="userName"
                filterable
                @change="passerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被转交人" prop="transfereeId">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="paramsObj.transfereeObj"
                :hide-select-list="transfereeHideSelect"
                :multiple="false"
                :value-type="'object'"
                :show-check-user="true"
                key-name="id"
                class="width240"
                label-name="userName"
                filterable
                @change="transfereeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :class="!showMobilePage && 'amount-item-row'" label="转交欠款(元)" prop="amount">
              <el-input
                v-model="paramsObj.amount"
                size="small"
                type="number"
                class="width240"
                placeholder="请输入转交欠款金额"
                oninput="if(value>999999999)value=999999999;if(value<-99999999)value=-99999999"
                @input="numInputChange($event, 'amount')"/>
              <div :class="showMobilePage && 'mobile-debt-text'" class="flex-center">
                <span style="margin-left: 8px; flex-shrink: 0">借款欠额：</span>
                <PriceColumn :real-val="totalDebt" :price="totalDebt" />
                <el-button
                  :disabeld="!totalDebt"
                  type="text"
                  style="margin-left: 8px; font-size: 14px"
                  @click="setTotalDebtToAmount">全部填入</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转交说明" prop="remark">
              <el-input
                v-model="paramsObj.remark"
                :maxlength="200"
                resize="none"
                class="width240"
                placeholder="请输入转交说明"
                type="textarea"
                size="small" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <audit-process
      ref="auditProcessRef"
      :loading="btnLoading"
      v-model="auditInfo"
      :old-audit-info="oldAuditInfo"
      :default-aduitor-list="[userInfo]"

      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="toSubmit(SUBMITTYPE.SUBMIT,$event)"
      @getProcess="getProcess" />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="(!remodifyId && !reapplyId) || createNew" :loading="btnLoading" type="primary" size="small" plain class="empty-btn-style" @click="toSubmit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="openDrawer">发起审批</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import SectionTitle from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import { isContained } from '@/utils/tools';
// api
import {
  storeArrearsTransferForm,
  getArrearsTransferDetail,
  createArrearsTransfer,
  editArrearsTransfer
} from '@/api/arrearsTransfer';
import { getInfo } from '@/api/login';
import { getDepartmentAll } from '@/api/config';
import { processManagementDetail } from '@/api/legal';
// util
import { SUBMITTYPE } from '@/utils/const/cost';
import { createAuditStructure } from '@/utils/aduitor';
import { showModal } from '@/utils/message';
import { FIXED_PROCESS_TYPE } from '@/utils/const/process';
import { hasRouteAuth } from '@/utils/permission';
// mixins
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { SectionTitle, selectWithUserLoad, AuditProcess, explanation },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      SUBMITTYPE,
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      btnLoading: false,
      isEdit: false,
      paramsObj: {
        departmentId: null,
        passerObj: {},
        passerId: '',
        passer: '',
        transfereeObj: {},
        transfereeId: '',
        transferee: '',
        amount: '',
        remark: ''
      },
      arrearsTransferId: '',
      reapplyId: '',
      deptTreeList: [],
      // 流程信息
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      totalDebt: 0, // 欠款总额
      processDetail: null,
      remodifyId: null, // 修改，审批流程不能修改
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      processId: null,
      isRefresh: false,
      createNew: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    rules() {
      return {
        'departmentId': [{ required: true, message: '请选择所属部门', trigger: 'change' }],
        'passerId': [{ required: true, message: '请选择转交人', trigger: 'change' }],
        'transfereeId': [{ required: true, message: '请选择被转交人', trigger: 'change' }],
        'amount': [{ required: true, message: '请输入转交欠款金额', trigger: 'blur' | 'change' }],
        'remark': [{ required: true, message: '请输入转交说明', trigger: 'blur' }]
      };
    },
    // 是否有修改转交人权限
    hasPasserAuth() {
      return hasRouteAuth('crm:arrearsTransfer:passer:change');
    },
    // 转交人默认值
    passerHideSelect() {
      if (!this.hasPasserAuth && this.arrearsTransferId) {
        return [{ id: this.userInfo.id, userName: this.userInfo.userName }];
      }
      const { passerId, passer } = this.paramsObj;
      return passerId && passer ? [{ id: passerId, userName: passer }] : [];
    },
    // 被转交人默认值
    transfereeHideSelect() {
      const { transfereeId, transferee } = this.paramsObj;
      return transfereeId && transferee ? [{ id: transfereeId, userName: transferee }] : [];
    }
  },
  created() {
    this.queryDeptTreeList();
    this.arrearsTransferId = Number(this.$route.params.id) || '';
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.remodifyId = this.$route.query.remodifyId; // 修改
    this.reapplyId = this.$route.query.reapplyId; // 重新申请
    if (this.arrearsTransferId) {
      this.isEdit = true;
      this.getDetail();
      this.reapplyId && this.getExplanation();
    } else {
      this.getPasserInfo(this.userInfo.id);
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        this.paramsObj.departmentId = this.getFirstDepartment(this.userInfo.departmentAry);
      }
      this.paramsObj.passerId = this.userInfo.id;
      this.paramsObj.passer = this.userInfo.userName;
      this.paramsObj.passerObj = {
        id: this.userInfo.id,
        userName: this.userInfo.userName
      };
      this.isEdit = false;
      this.getExplanation();
    }
  },
  methods: {
    toDetail() {
      const { id, processId } = this.paramsObj;
      this.$router.push({
        name: 'arrearsTransferDetail',
        query: {
          id,
          processId,
          fromList: 1
        }
      });
    },
    // // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    setTotalDebtToAmount() {
      if (!this.totalDebt && this.totalDebt !== 0) {
        this.paramsObj.amount = null;
      } else {
        this.paramsObj.amount = this.totalDebt.toFixed(2);
      }
    },
    // 限制借款金额
    numInputChange(text, prop) {
      if (text == null || text === '') {
        this.paramsObj[prop] = null;
        return;
      }
      let str = text.replace(/[^\-?\d.]/g, ''); // 只允许正负数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(-?\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
      this.paramsObj[prop] = Number(str) <= 0 ? str : Number(str) <= this.totalDebt ? str : this.totalDebt;
    },
    passerChange(data) {
      this.getTotalDebt(data);
      this.paramsObj.passerId = data.id;
      this.paramsObj.passer = data.userName;
    },
    transfereeChange(data) {
      this.paramsObj.transfereeId = data.id;
      this.paramsObj.transferee = data.userName;
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: FIXED_PROCESS_TYPE.ARREARS_TRANSFER }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    getDetail() {
      getArrearsTransferDetail(this.arrearsTransferId).then(res => {
        if (res.code === 200) {
          this.getPasserInfo(this.hasPasserAuth ? res.data.passerId : this.userInfo.id);
          this.paramsObj = res.data;
          if (this.paramsObj.amount || this.paramsObj.amount === 0) {
            this.paramsObj.amount /= 100;
          }
          // 如果没有修改转交人权限，转交人修改为当前用户
          const passerObj = this.hasPasserAuth ? { id: this.paramsObj.passerId, userName: this.paramsObj.passer } : { id: this.userInfo.id, userName: this.userInfo.userName };
          this.$set(this.paramsObj, 'passerObj', passerObj);
          if (!this.hasPasserAuth) {
            this.paramsObj.passer = this.userInfo.userName;
            this.paramsObj.passerId = this.userInfo.id;
          }
          this.$set(this.paramsObj, 'transfereeObj', {
            id: this.paramsObj.transfereeId,
            userName: this.paramsObj.transferee
          });
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = _.cloneDeep(res.data.auditInfo);
            this.processDetail = _.cloneDeep(res.data.auditInfo);
          }
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          if (this.arrearsTransferId) {
            this.$refs.baseform.resetFields();
          }
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      });
    },
    getPasserInfo(id) {
      getInfo(id).then(res => {
        this.getTotalDebt(res.data);
      });
    },
    getTotalDebt(data) {
      const owedAmount = data && data.financialInfo && data.financialInfo.owedAmount;
      if (isNaN(owedAmount)) return 0;
      this.totalDebt = owedAmount / 100;
    },
    handleParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      delete params.passerObj;
      delete params.transfereeObj;
      return params;
    },
    toSubmit(submitType = SUBMITTYPE.SUBMIT, senders = []) {
      this.modifySenders = senders;// 存到mixins
      // 处理参数
      const params = this.handleParams();
      params.submitType = submitType;
      if (submitType !== SUBMITTYPE.DRAFT && this.reapplyId && !this.createNew) { // 重新提交
        params.submitType = SUBMITTYPE.RESUBMIT;
      }
      // 修改时，流程被编辑或者更新
      params.isEditAudit = !!(this.remodifyId && this.isRefresh);
      if (this.createNew) {
        delete params.id;
      }
      params.auditInfo = this.auditInfo;
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      if (this.isEdit && !this.createNew) {
        showModal(msg).then(() => {
          this.handleModifyData(params);
          this.edit(params);
        });
      } else {
        showModal(msg).then(() => this.create(params));
      }
    },
    // 流程相关 start
    openDrawer() { // 流程弹窗
      try {
        const params = [];
        params.push(this.$refs.baseform.validate());
        Promise.all(params).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            const logicResult = this.dataLogicValidate();
            logicResult && this.getProcessDetail();
          } else {
            return false;
          }
        }).catch(() => {
          this.$message.warning('请检查信息是否填写完整');
        });
      } catch (error) {
        console.log(error);
      }
    },
    dataLogicValidate() {
      const { amount, transfereeId, passerId } = this.paramsObj;
      if (amount > this.totalDebt) {
        this.$message.warning('转交欠款不能大于欠款总额');
        return false;
      } else if (Number(amount) === 0) {
        this.$message.warning('转交欠款不能为0');
        return false;
      } else if (passerId === transfereeId) {
        this.$message.warning('转交人和被转交人不能相同');
        return false;
      }
      return true;
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    getProcessDetail(isRefresh) {
      const params = this.handleParams();
      params.type = FIXED_PROCESS_TYPE.ARREARS_TRANSFER;
      this.btnLoading = true;
      storeArrearsTransferForm(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcessRef'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcessRef'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    // 流程相关 end
    create(params) {
      this.btnLoading = true;
      createArrearsTransfer(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'arrearsTransferDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        this.btnLoading = false;
      });
    },
    edit(params) {
      this.btnLoading = true;
      editArrearsTransfer(this.arrearsTransferId, params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.processId) {
            this.$router.push({
              name: 'arrearsTransferDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'arrearsTransferDetail', params: {}, query: { id: this.arrearsTransferId, processId: this.remodifyId }});
        }
        this.btnLoading = false;
      });
    },
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    toBack() {
      if (this.remodifyId) {
        this.processId = this.remodifyId;
      }
      if (this.reapplyId) {
        this.processId = this.reapplyId;
      }
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'arrearsTransferDetail',
          query: {
            id: this.id,
            processId: this.processId
          }
        });
        return;
      }
      this.$router.push({ name: 'arrearsTransfer' });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-debt-wrap{
  .width240 {
    width: 240px;
  }
  .page-container{
    padding: 20px 24px 24px;
    .amount-item-row {
      ::v-deep .el-form-item__content {
        display: flex;
        align-items: center;
      }
    }
    .mobile-debt-text {
      height: 1.2em;
      margin-top: 6px;
      > span {
        margin-left: 0 !important;
      }
    }
  }
  margin: 16px;
  background: #FFFFFF;
  min-height: calc(100vh - 80px);
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    width: 80px;
    padding: 7px 0;
    text-align: center;
  }
  .explanation{
    padding-left: 9px;
  }
  ::v-deep .el-range-separator{
    width: 20px;
  }
}
::v-deep .el-cascader--large {
  width: 100%;
}
.grey-label {
  &::v-deep {
    .el-form-item__label {
      color: #999 !important;
    }
  }
}
</style>
